package com.campuscarbooking.api.repository;

import com.campuscarbooking.api.model.Reservation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface ReservationRepository extends JpaRepository<Reservation, Long> {

    Page<Reservation> findByUserId(Long userId, Pageable pageable);

    Page<Reservation> findByUserIdAndStatus(Long userId, Reservation.Status status, Pageable pageable);

    @Query("SELECT r FROM Reservation r JOIN r.schedule bs WHERE r.user.id = ?1 AND bs.departureTime >= ?2 AND bs.departureTime < ?3")
    List<Reservation> findByUserIdAndDepartureDate(Long userId, LocalTime startOfDay, LocalTime endOfDay);

    @Query("SELECT r FROM Reservation r WHERE r.schedule.id = ?1")
    List<Reservation> findByScheduleId(Long scheduleId);

    @Query("SELECT COUNT(r) FROM Reservation r WHERE r.user.id = ?1 AND r.status = 'canceled' AND r.canceledAt >= ?2")
    int countCancelledReservationsToday(Long userId, LocalDateTime startOfDay);

    Optional<Reservation> findByIdAndUserId(Long id, Long userId);

    @Query("SELECT COUNT(r) FROM Reservation r " +
            "WHERE r.schedule.id = ?1 AND r.status <> 'canceled'")
    Integer countActiveReservationsByScheduleId(Long scheduleId);

    @Query("SELECT r FROM Reservation r " +
            "WHERE r.schedule.id = ?1 AND r.status <> 'canceled' " +
            "ORDER BY CASE WHEN r.user.userType = 'teacher' THEN 0 ELSE 1 END")
    List<Reservation> findActiveReservationsByScheduleIdOrderByUserType(Long scheduleId);

    @Query("SELECT r FROM Reservation r JOIN r.schedule bs WHERE bs.departureTime >= ?1 AND bs.departureTime < ?2")
    List<Reservation> findByDepartureTimeBetween(LocalTime startTime, LocalTime endTime);

    @Query("SELECT r FROM Reservation r JOIN r.schedule bs " +
            "WHERE bs.departureTime >= ?1 AND bs.departureTime < ?2")
    Page<Reservation> findByDepartureTimeBetween(LocalTime startTime, LocalTime endTime, Pageable pageable);
} 